package net.bplaced.streetfighter;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.bplaced.streetfighter.lib.async.task.MatchScoreLoaderTask;
import net.bplaced.streetfighter.lib.model.Match;
import net.bplaced.streetfighter.lib.model.MatchScore;
import net.bplaced.streetfighter.lib.model.Team;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.RuntimeData;
import net.bplaced.streetfighter.lib.utils.RuntimeDataKey;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import net.bplaced.streetfighter.lib.utils.StreetfighterUtils;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.de>
 */
public class MatchDetailActivity
        extends Activity {

    private Match matchItem;

    Intent _mapsIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

// final Intent i = this.getIntent();
// final Bundle b = i.getExtras();
// this.matchItem = (Match) b.getParcelable(Match.INTENTKEY_MATCH);
        this.matchItem = (Match) RuntimeData.getInstance().get(RuntimeDataKey.MATCH).getData();

        this.setContentView(R.layout.match_detail);

        // Opponent
        final TextView opponentField = (TextView) this.findViewById(R.id.match_detail_opponent);
        opponentField.setText(this.matchItem.opponent);

        if (this.matchItem.matchCategory == 2) {
            opponentField.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.category_gradient_heim));
        } else if (this.matchItem.matchCategory == 3) {
            opponentField
                    .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.category_gradient_auswaerts));
        } else if (this.matchItem.matchCategory == 4) {
            opponentField.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.category_gradient_pokal));
        } else if (this.matchItem.matchCategory == 5) {
            opponentField.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.category_gradient_playoff));
        } else if (this.matchItem.matchCategory == 6) {
            opponentField
                    .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.category_gradient_testspiel));
        }

        final Date tempDateTime = StreetfighterUtils.convertToDate(this.matchItem.matchDate, this.matchItem.matchTime);

        // Date
        final TextView dateField = (TextView) this.findViewById(R.id.match_detail_date);
        dateField.setText(new SimpleDateFormat("dd.MM.yyyy").format(tempDateTime));

        // Time
        final TextView timeField = (TextView) this.findViewById(R.id.match_detail_time);
        timeField.setText(new SimpleDateFormat("HH:mm").format(tempDateTime));

        // Location name
        final TextView locationNameField = (TextView) this.findViewById(R.id.match_detail_locationName);
        locationNameField.setText(this.matchItem.locationName);

        // Location street
        final TextView locationStreetField = (TextView) this.findViewById(R.id.match_detail_locationStreet);
        locationStreetField.setText(this.matchItem.locationStreet);

        // PostCode
        final TextView postCodeField = (TextView) this.findViewById(R.id.match_detail_locationPostCode);
        postCodeField.setText(this.matchItem.locationPostCode.toString());

        // City
        final TextView cityField = (TextView) this.findViewById(R.id.match_detail_locationCity);
        cityField.setText(this.matchItem.locationCity);

        this._mapsIntent = new Intent();
        this._mapsIntent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");

        final Button showMapsButton = (Button) this.findViewById(R.id.match_detail_showMap);
        showMapsButton.setEnabled(StreetfighterUtils.isAppInstalled(this, this._mapsIntent));

        showMapsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                MatchDetailActivity.this._mapsIntent.setAction(android.content.Intent.ACTION_VIEW);
                MatchDetailActivity.this._mapsIntent.setData(Uri.parse(new StringBuilder(
                        "http://maps.google.com/maps?q=")
                        .append(MatchDetailActivity.this.matchItem.locationLatitude.toString()).append(",")
                        .append(MatchDetailActivity.this.matchItem.locationLongitude.toString()).append("&z=")
                        .append(MatchDetailActivity.this.matchItem.locationZoom.toString()).append("mrt=yp").toString()));
                MatchDetailActivity.this.startActivity(MatchDetailActivity.this._mapsIntent);
            }
        });

        final Team ownTeam = ((Team) RuntimeData.getInstance().get(RuntimeDataKey.HOME_TEAM).getData());
        final MatchScoreLoaderTask task =
                new MatchScoreLoaderTask(this, this.getResources().getString(R.string.match_detail_progress_message),
                        this.onFinishedLoading);
        task.execute(ownTeam.name, this.matchItem.opponent, this.matchItem.matchCategory.toString());
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<MatchScore>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<MatchScore>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<MatchScore> result) {

                    if (result != null) {
                        if (result.getContent() != null) {

                            MatchDetailActivity.this.createOpponentStats(result.getContent());

                        } else {

                            Toast.makeText(MatchDetailActivity.this, result.getErrorMessage(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                };
            };

    private void createOpponentStats(MatchScore score) {

        final LinearLayout opponentLayout =
                (LinearLayout) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_data_layout);
        final TableRow matchScoreRow =
                (TableRow) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_data_match_score_row);

        if (score.homeTeam != null) {

            opponentLayout.setVisibility(View.VISIBLE);

            final TextView rankField =
                    (TextView) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_rank);
            rankField.setText(score.guestTeam.rank.toString());

            final TextView goalPercentageField =
                    (TextView) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_goalpercentage);
            goalPercentageField.setText(score.guestTeam.getGoalPercentage());

            final TextView goalDifferenceField =
                    (TextView) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_goaldiff);
            goalDifferenceField.setText(score.guestTeam.getGoalDiff().toString());

            final TextView pointsField =
                    (TextView) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_points);
            pointsField.setText(score.guestTeam.getPoints().toString());

            if (score.homeTeamGoals != null) {

                matchScoreRow.setVisibility(View.VISIBLE);
                final TextView scoreField =
                        (TextView) MatchDetailActivity.this.findViewById(R.id.match_detail_opponent_data_match_score);
                scoreField.setText(new StringBuilder(score.homeTeamGoals.toString()).append(":").append(
                        score.guestTeamGoals.toString()));
            } else {
                matchScoreRow.setVisibility(View.INVISIBLE);
            }

        } else {

            opponentLayout.setVisibility(View.INVISIBLE);
        }
    }
}